var form = layui.form,table = layui.table, $ = layui.jquery, id = getQueryVariable("id"),annexList = [];
var data0 = [];
var data1 = [];
var data2 = [];
var data3 =[]
$('#editor-form').find('input,textarea,select').attr('disabled',true);

//表单初始值，修改时调用
if (id != "") {
    form.val("editor-form", {
        "invoicenumber": "进入查看明细",
    })
}
var bill=[];
var products=[];
var    parts=[];
$(document).ready(function () {

    getInfo()
    table.reload('storageproductstableid',{
        data:products
    })
    showInfo()
        //加载附件
        $.ajax({
            url: 'clearChange/selectBillFile?type=3&parentId='+id,
            type: 'GET',
            success: function (date) {
                annexList = date.data;
                table.reload('attachmenttableid', {data:date.data});;
            }
        });
})
function  showInfo() {
    var info=bill[0]
    $("input[name='customername']").val(info.customerName);
    $("input[name='idate']").val(info.invoiceDate);
    $("input[name='shdate']").val(info.shippingDate);
    $("input[name='edrdate']").val(info.settleDate);
    $("input[name='invoicenumber']").val(info.invoiceNo);
    $("input[name='currency']").val(info.moneyKind);
    $("input[name='exchangerate']").val(info.usdRate);
    $("input[name='rmbexchangerate']").val(info.rmbRate);
    $("input[name='place']").val(info.startPlace);
    $("input[name='destination']").val(info.endPlace);
    $("input[name='settlementway']").val(info.settleMode);
    $("input[name='priceterms']").val(info.priceTerm);
    $("input[name='invoicetotalamount']").val(info.invoiceMoney);
    $("input[name='salescontractno']").val(info.contractNo);
    $("input[name='customercontractno']").val(info.custContractNo);
    $("input[name='salesman']").val(info.salesman);
    $("input[name='businessmodel']").val(info.businessMode);
    $("input[name='asperinno']").val(info.asPerInNo);
    $("input[name='warehouse']").val(info.stock);
    $("input[name='withinlimit']").val(info.overdue);
    $("input[name='containertype']").val(info.payday);
    $("input[name='signingcompany']").val(info.companyName);
    $("input[name='bank']").val(info.bankName);
    $("input[name='theoperator']").val(info.opname);
    $("input[name='totaltariffamount']").val(info.totalTariffAmount);
    $("input[name='actualdischargedateatd']").val(info.actualAtd);
    $("input[name='wldate']").val(info.instockDate);
    // $("input[name='clearAllPlace']").val(info.clearAllPlace);
    // $("input[name='clear_1']").val(info.clear_1);
    // $("input[name='clear_2']").val(info.clear_2);
    // $("input[name='clear_3']").val(info.clear_3);
    var s="否"
    if(info.clear_1==1){
        s="是"
    }
    $("input[name='clear_1']").val(s);
    $("input[name='clear_2']").val(info.clear_2);
    form.render();
}
function getInfo(){
    $.ajax({
        url: 'clearChange/selectInfoBillById?clearId='+id,
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            var map=date.data;
            $.each(map, function (key, value) {
                if(key=="clear"){
                    bill=value
                }
                if(key=="products"){
                    products=value
                }
                if(key=="parts"){
                    parts=value
                }
                if(key=="costs"){
                    var costs=value
                    table.reload('costtableid',{
                        data:costs
                    })
                }
            });
        }
    });
}



form.render();
//--产品信息
table.render({
    elem: '#storageproducts',
    id: 'storageproductstableid',
    data: data0,
    toolbar: '#storageproductstoolbar',
    cols: [[
        {field: 'stockNo', width: 120, title: '采购单号'},
        {field: 'goodsCode', width: 120, title: '产品编码'},
        {field: 'specCode', width: 120, title: '规格编码'},
        {field: 'specNo', width: 120, title: '规格说明'},
        {field: 'goodsCname', width: 120, title: '中文名称'},
        {field: 'goodsEname', width: 120, title: '英文名称'},
        {field: 'goodsCdesc', width: 120, title: '中文描述'},
        {field: 'goodsEdesc', width: 120, title: '英文描述'},
        {field: 'goodsNum', width: 80, title: '产品数量'},
        {field: 'lastAmount', width: 140, title: '本次清关数量'},
        {field: 'clearOnePlace', width: 120, title: '清关单价'},
        {field: 'clearAllPlace', width: 120, title: '清关总价'},
        {field: 'goodsUnit', width: 120, title: '单位'},
        {field: 'funitprice', width: 80, title: '单价'},
        {field: 'ftotalprice', width: 120, title: '金额小计'},
        {field: 'color', width: 120, title: '颜色'},
        {field: 'goodsGross', width: 120, title: '毛重'},
        {field: 'totalGross', width: 120, title: '毛重小计' },
        {field: 'netweight', width: 120, title: '净重'},
        {field: 'totalNet', width: 120, title: '净重小计'},
        {field: 'bulk', width: 120, title: '体积'},
        {field: 'totalBulk', width: 120, title: '体积小计'},
        {field: 'totalTray', width: 120, title: '托数'},
        {field: 'trayNum', width: 120, title: '每托量'},
        {field: 'piecesNum', width: 120, title: '件数'},
        {field: 'perpiecesNum', width: 120, title: '每件数量'},
        {field: 'paymentpaymentdays', width: 120, title: '付款账期'},
        {field: 'costUnitPrice', width: 120, title: '成品单价'},
        {field: 'accessoriesCost', width: 120, title: '配件成本'},
        {field: 'finishedProductCost', width: 120, title: '成品成本'},
        {field: 'supplyerName', width: 120, title: '供应商'},
        {field: 'saleContractNo', width: 120, title: '外销合同号'},
        {field:'tariffRate', title:'关税税率', width: 120},
        {field:'tariffMoney', title:'关税金额', width: 120},
        {fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#storageproductseditor'}
    ]],
    page: true,
    height: 380
});
//监听行单击事件
table.on('row(storageproductstable)', function(obj){

    var clearid= obj.data.clearId
    var clearProductId=obj.data.clearProductId
    var showPart=[]
    for(let i in parts){
        if(parts[i].clearId==clearid&&parts[i].clearProductId==clearProductId){
            showPart.push(parts[i])
        }
    }
    $("#hidden").show();
    table.render({
        elem: '#productsaselect'
        ,data:showPart
        ,toolbar: '#productsatoolbar'
        ,where:{id:obj.data.id} //查询的产品ID，条件
        ,cols: [[
             {field: 'goodsCode', title: '产品编码'}
            ,{field: 'specCode', title: '规格编码'}
            ,{field:'cpbl', title:'成品比例'}
            ,{field:'pebl', title:'配件比例'}
            ,{field:'goodsnumParts', title:'配件数量'}
            ,{field:'lastAmount', title:'本次清关数量',width: 140}
            ,{field: 'costUnitPrice', width: 120, title: '成本单价'}
            ,{field: 'costSubtotal', width: 120, title: '成本小计'}
            ,{field: 'stockNo', width: 120, title: '采购单号'}
            ,{field: 'supplyerName', width: 120, title: '供应商'}
            ,{field:'goodsCname', title:'中文名称'}
            ,{field:'goodsEname', title:'英文名称'}
            ,{field:'goodsGross', title:'毛重'}
            ,{field:'netWeight', title:'净重'}
            ,{field:'bulk', title:'体积'}
        ]]
        ,id: 'productsatableid'
        ,page: true
        ,height:300
    });
});
//---费用
table.render({
    elem: '#cost'
    , data: []
    , toolbar: '#costtoolbar'
    , cols: [[
        {checkbox: true, fixed: true}
        , {field: 'costType', title: '费用类型',templet:"#costtypeselect"}
        , {field: 'costMoney', title: '金额',event:'amount'}
        , {field: 'costDesc', title: '备注说明'}
        , {field: 'contractNo', title: '外销合同号'}
    ]]
    , id: 'costtableid'
    , height: 380
    , page: true
    , done: function (res, curr, count) {
        $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
        $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
        var cost= getCost();
        for(let i in cost){
            $(".costType").append(new Option(cost[i].name,cost[i].code));
        }
        for (var i = 0; i < res.data.length; i++) {
            $('.costType:eq('+i+') option[value="'+res.data[i].costType+'"]').prop("selected",true);
        }
        form.render('select');
    }
});
function   getCost(){
    var  cost1= getdictionary(5,19)
    var cost=new Array();
    for(let i in cost1){
        cost.push(cost1[i])
    }
    return cost

}
//---附件
table.render({
    elem: '#attachment'
    , data:annexList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'fileName', title: '文件名', fixed: true}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    } else if (obj.event === 'del') {
        layer.confirm('确认删除?', function (index) {
            obj.del();
            let id = data.id;
            for (var i = 0; i < annexList.length; i++) {
                if (annexList[i].id == id) {
                    annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                    i--; // 如果不减，将漏掉一个元素
                    break;
                }
            }
            layer.msg("删除成功", {icon: 6});
            layer.close(index);
            table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
        });
    }
});

//---操作日志
table.render({
    url:'clearChange/selectBillClearLogsByPage?billNo='+id
    ,elem: '#otherwarehouselog'
    , data: data2
    , cols: [[
        {field: 'type', title: '操作类型', fixed: true}
        , {field: 'optioner', title: '操作员'}
        , {field: 'option_time', title: '操作日期'}
        , {field: 'content', title: '修改内容'}
    ]]
    , id: 'logtableid'
    , height: 380
    , limit: 30//显示的数量
    , page: true
});